<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.username" size="medium" clearable placeholder="用户名" style="width: 200px;" class="filter-item"/>
      <el-input v-model="listQuery.mobile" size="medium" clearable placeholder="手机" style="width: 200px;" class="filter-item"/>
      <el-button class="filter-item" size="medium" style="margin-left: 20px;" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" type="warning" size="medium" style="margin-left: 50px;" @click="createAdmin">添加管理员</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row>
      <el-table-column type="selection" width="50"/>
      <el-table-column label="用户名">
        <template slot-scope="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="昵称">
        <template slot-scope="scope">
          {{ scope.row.nickname }}
        </template>
      </el-table-column>
      <el-table-column label="手机">
        <template slot-scope="scope">
          {{ scope.row.mobile }}
        </template>
      </el-table-column>
      <el-table-column label="邮箱">
        <template slot-scope="scope">
          {{ scope.row.email }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1" active-color="#13ce66" @change="handleSetStatus(scope.row)"/>
          <el-tooltip class="item" effect="dark" content="重置密码" placement="top">
            <el-button style="margin: 0 10px;" size="mini" type="primary" circle @click="resetPass(scope.row)"><svg-icon icon-class="resetpass" /></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="list.length > 0" class="pagination-container">
      <el-pagination :current-page="listQuery.currentPage" :page-sizes="[10,25,50,100]" :page-size="listQuery.pageSize" :total="total" background layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
    </div>
    <!--添加管理员-->
    <el-dialog :visible.sync="dialogFormVisible" :title="isReset ? '重置密码' : '添加管理员'" center width="40%">
      <el-form ref="dataForm" :label-width="formLabelWidth" :rules="rules" :model="form">
        <el-form-item v-show="!isReset" label="用户名" prop="username">
          <el-input v-model="form.username" auto-complete="off"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" auto-complete="off"/>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmpwd">
          <el-input v-model="form.confirmpwd" type="password" auto-complete="off"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click.native.prevent="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { createAdmin } from '@/api/oauth'
import { getUserList, setUserStatus, resetPassword } from '@/api/user'

export default {
  name: 'Administrator',
  data() {
    const validatePass = (rule, value, callback) => {
      if (this.form.confirmpwd !== '') {
        this.$refs.dataForm.validateField('confirmpwd')
      }
      callback()
    }
    const validateConfirmpass = (rule, value, callback) => {
      if (this.form.password !== '' && value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    return {
      isReset: false,
      dialogFormVisible: false,
      form: {
        username: '',
        password: '',
        confirmpwd: ''
      },
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }, { validator: validatePass, trigger: 'blur' }],
        confirmpwd: [{ validator: validateConfirmpass, trigger: 'blur' }]
      },
      formLabelWidth: '100px',
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        currentPage: 1,
        pageSize: 25,
        username: '',
        mobile: ''
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    /* 获取管理员列表 */
    fetchData() {
      this.listLoading = true
      getUserList(this.listQuery).then(response => {
        if (response.data) {
          this.list = response.data
          this.total = response.total
        }
      }).finally(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.currentPage = 1
      this.fetchData()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.currentPage = val
      this.fetchData()
    },
    resetForm() {
      this.form = {
        username: '',
        password: '',
        confirmpwd: ''
      }
    },
    createAdmin() {
      this.isReset = false
      this.resetForm()
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    resetPass(row) {
      this.isReset = true
      this.resetForm()
      this.form.username = row.username
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    submitForm() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.isReset) {
            resetPassword(this.form).then(() => {
              this.actiniaSucc('重置密码成功')
            })
          } else {
            createAdmin(this.form).then(() => {
              this.actiniaSucc('添加管理员成功')
              this.fetchData()
            })
          }
          this.dialogFormVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleSetStatus(row) {
      let msg = '您将启用该用户，是否继续？'
      if (row.status === 1) {
        msg = '您将禁用该用户，是否继续？'
      }
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          'username': row.username,
          'status': row.status
        }
        setUserStatus(data).then(() => {
          this.actiniaSucc('用户状态修改成功')
          this.fetchData()
        })
      }).catch(() => {
        console.log('cancel setstatus')
        this.fetchData()
      })
    }
  }
}
</script>
